﻿using System;
using System.Web.Mvc;
using YuFeng.Models.WechatCorp;
using YuFeng.Services.User;
using YuFeng.Web.Helpers;
using RestSharp;
using YuFeng.Web.Extentions;
using System.Net;
using System.Web.Script.Serialization;
using System.Collections.Generic;

namespace YuFeng.Web.Controllers
{
    public class WechatCorpAuthController : BaseController
    {
        private readonly IUserService _userService;

        private readonly string _appID = "wxdbaad22a688cd56a";
        private readonly string _appsecret = "768c2d0ca69748dd6bf4bd238bb92b82";

        private readonly string _apiWechatServiceBaseUrl = "https://api.weixin.qq.com";
        private readonly string _apiGetAccessToken = "/cgi-bin/token?appid={0}&secret={1}&grant_type=client_credential";
        private readonly string _apiGetUserIdByCode = "/cgi-bin/user/getuserinfo?access_token={0}&code={1}";
        private readonly string _apiDeleteMenu = "/cgi-bin/menu/delete?access_token={0}";
        private readonly string _apiCreateMenu = "/cgi-bin/menu/create?access_token={0}";
        private readonly string _apiGetCode = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_base&state={2}#wechat_redirect";



        private readonly string _keyState = "CURRENT_STATE";
        private readonly string _keyReturnUrl = "RETURN_URL";

        public WechatCorpAuthController(IUserService userService)
        {
            _userService = userService;
        }

        #region private functions

        private WechatCorpAccessTokenResponseDto GetAccessToken(string code)
        {
            string url = string.Format(_apiWechatServiceBaseUrl + _apiGetAccessToken, _appID, _appsecret, code);
            HttpGet httpGet = new HttpGet(url);
            var result = httpGet.Request();
            WechatCorpAccessTokenResponseDto accessTokenWithOpenID = JsonHelper.JsonToObj<WechatCorpAccessTokenResponseDto>(result);
            return accessTokenWithOpenID;
        }
        public ActionResult SyncMenu()
        {
            var token = GetToken().access_token;
            //删除目录
            var deleteUrl = string.Format(_apiWechatServiceBaseUrl + _apiDeleteMenu, token);
            var deleteReq = new HttpPost(deleteUrl);
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
            var data = deleteReq.Request();
            var deleteMsg = (new JavaScriptSerializer()).Deserialize<ErrorMsg>(data);
            //创建目录
            var createUrl = string.Format(_apiWechatServiceBaseUrl + _apiCreateMenu, token);
            List<Menu> menuList = new List<Menu> {
                new Menu(YuFeng.Models.AppEnum.MenuType.view, "御丰商城", "http://wap.koudaitong.com/v2/feature/1ejl3ictg"),
                new Menu(YuFeng.Models.AppEnum.MenuType.view, "御丰官网", "http://yufeng.mianfangyun.com/Home/index"),
                new Menu(YuFeng.Models.AppEnum.MenuType.view ,"联系我们","http://yufeng.mianfangyun.com/Home/ContactUs")
            };
            var result = CreateMenu(menuList, createUrl);
            return SuccessMsg(result.errcode + result.errmsg);
        }
        /// <summary>
        /// 获取用户
        /// </summary>
        /// <returns></returns>
        private WechatCorpUser GetUser(string accessToken, string code)
        {
            string url = string.Format(_apiGetUserIdByCode, accessToken, code);
            var client = new RestClient(_apiWechatServiceBaseUrl);
            var request = new RestRequest(url, Method.GET);
            request.Resource = url;
            IRestResponse<WechatCorpUser> response = client.Execute<WechatCorpUser>(request);
            return response.Data;
        }
        #endregion
        public ActionResult Go()
        {
            string state = DateTime.Now.Ticks.ToString();
            Session[_keyState] = state;
            Session[_keyReturnUrl] = ReturnUrlHelper.GetReturnUrl(string.Empty, Url.Action("Index", "Home"));

            string redirectUrl = ReturnUrlHelper.CurrentSiteUrl + Url.Action("CallBack", "WechatCorpAuth");

            string url = string.Format(_apiGetCode, _appID, Url.Encode(redirectUrl), state);
            return Redirect(url);
        }

        //public ActionResult CallBack(string code, string state)
        //{
        //    if ((string)Session[_keyState] != state || string.IsNullOrEmpty(state))
        //        return HttpNotFound();
        //    var accessToken = GetAccessToken();
        //    var userResponse = GetUser(accessToken.AccessToken, code);
        //    if (userResponse == null)
        //        return Content("授权失败！");
        //    var user = _userService.GetUserByName(userResponse.UserId);
        //    if (user == null)
        //        return Content("用户不存在！");
        //    SessionContext.SignIn(user);
        //    var returnUrl = ReturnUrlHelper.GetReturnUrl(Session[_keyReturnUrl] as string, Url.Action("Index", "Home"));
        //    return Redirect(returnUrl);
        //}
        public ErrorMsg CreateMenu(List<Menu> list, string requestUrl)
        {
            try
            {
                var postdata = new System.Text.StringBuilder();
                postdata.Append("{\"button\":[");
                for (var i = 0; i < list.Count; i++)
                {
                    //不是第一条数据，前面加“,”分开
                    if (i > 0)
                    {
                        postdata.Append(",");
                    }
                    //判断是否有子菜单
                    if (list[i].sub_button == null || list[i].sub_button.Count < 1)
                    {
                        postdata.Append(this.MenuJson(list[i]));

                    }
                    else
                    {
                        postdata.Append("{\"name\": \"" + list[i].name.JsonValue() + "\", \"sub_button\": [");
                        for (var j = 0; j < list[i].sub_button.Count; j++)
                        {
                            //不是第一条数据，前面加“,”分开
                            if (j > 0)
                            {
                                postdata.Append(",");
                            }
                            postdata.Append(this.MenuJson(list[i].sub_button[j]));
                        }
                        postdata.Append("]}");
                    }
                }
                postdata.Append("]}");
                var req = new HttpPost(requestUrl);
                req.PostData = postdata.ToString();//.ToLower();
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
                var data = req.Request();
                return (new JavaScriptSerializer()).Deserialize<ErrorMsg>(data);
            }
            catch (Exception ex)
            {
                throw new Exception("MenuCreate:" + ex.Message);

            }
        }
        private string MenuJson(Menu t)
        {
            switch (t.type)
            {
                case YuFeng.Models.AppEnum.MenuType.click:
                case YuFeng.Models.AppEnum.MenuType.scancode_waitmsg:
                case YuFeng.Models.AppEnum.MenuType.scancode_push:
                case YuFeng.Models.AppEnum.MenuType.pic_sysphoto:
                case YuFeng.Models.AppEnum.MenuType.pic_photo_or_album:
                case YuFeng.Models.AppEnum.MenuType.pic_weixin:
                case YuFeng.Models.AppEnum.MenuType.location_select:
                default:
                    return JsonTemplate.MenuClick.Replace("[type]", t.type.ToString()).Replace("[name]", t.name.JsonValue()).Replace("[key]", t.value.JsonValue());

                case YuFeng.Models.AppEnum.MenuType.view:
                    return JsonTemplate.MenuView.Replace("[type]", t.type.ToString()).Replace("[name]", t.name.JsonValue()).Replace("[url]", t.value.JsonValue());
            }
        }

        public Token GetToken()
        {
            try
            {
                var req = new HttpGet(string.Format(_apiWechatServiceBaseUrl + _apiGetAccessToken, _appID, _appsecret));
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
                var data = req.Request();
                return (new JavaScriptSerializer()).Deserialize<Token>(data);
            }
            catch (Exception ex)
            {
                throw new Exception("AccessToken:" + ex.Message);

            }
        }
    }
}